package net.jiastudy.core.base;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import net.jiastudy.biz.user.entity.User;
import net.jiastudy.core.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class BaseService<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	protected ApplicationContext applicationContext;

	@Resource
	protected ApplicationEventPublisher applicationEventPublisher;

	@Resource
	protected RedisTemplate<String, T> redisTemplate;

	protected User getCurrentUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (null != authentication && null != authentication.getPrincipal()) {
			return (User) authentication.getPrincipal();
		}
		return null;
	}

	protected void generateSort(Wrapper<?> wrapper, Sort sort) {
		if (null == wrapper || null == sort) {
			return;
		}
		filterSortField(sort);
		for (Iterator<Order> iter = sort.iterator(); iter.hasNext();) {
			Order order = iter.next();
			if (order.getDirection() == Direction.ASC) {
				wrapper.orderBy(order.getProperty(), true);
			} else {
				wrapper.orderBy(order.getProperty(), false);
			}
		}
	}

	protected String generateOrderByStr(Sort sort) {
		if (null == sort) {
			return null;
		}
		filterSortField(sort);
		StringBuilder sb = new StringBuilder("order by ");
		for (Iterator<Order> iter = sort.iterator(); iter.hasNext();) {
			Order order = iter.next();
			sb.append(this.filterOrderByStr(order.getProperty())).append(" ").append(order.getDirection()).append(" ,");
		}
		sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	}

	protected void filterSortField(Sort sort) {
		for (Iterator<Order> iter = sort.iterator(); iter.hasNext();) {
			Order order = iter.next();
			if (!this.sortFields().contains(order.getProperty().toLowerCase())) {
				throw new ServiceException("非法的排序字段");
			}
		}
	}

	protected Set<String> sortFields() {
		Set<String> fields = new HashSet<>();
		fields.add("id");
		fields.add("seq");
		return fields;
	}

	protected String filterOrderByStr(String str) {
		return str.replace(" ", "").replace(";", "").replace(",", "").replace("(", "").replace(")", "");
	}
}
